﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using Monkey.Warrenty.Data.Interfaces;
using Monkey.Warrenty.EntityModel;

namespace Monkey.Warrenty.Data
{
    public class CustomerGroupDao : ICustomerGroupDao
    {
        public List<CustomerGroup> GetAllCustomerGroups()
        {
            List<CustomerGroup> customerGroups;

            using (var context = new MonkeyWarrantyEntities())
            {
                customerGroups = context.CustomerGroups.OrderBy(x => x.Name).ToList();
            }

            return customerGroups;
        }

        public CustomerGroup AddCustomerGroup(CustomerGroup customerGroup)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                context.CustomerGroups.AddObject(customerGroup);
                context.SaveChanges();
            }

            return customerGroup;
        }

        public void UpdateCustomerGroup(CustomerGroup customerGroup)
        {
            // throw new System.NotImplementedException();
            if (customerGroup == null || customerGroup.Id == 0) return;

            using (var context = new MonkeyWarrantyEntities())
            {
                context.CustomerGroups.Attach(customerGroup);
                context.ObjectStateManager.ChangeObjectState(customerGroup, EntityState.Modified);
                context.SaveChanges();
            }
        }

        public void DeleteCustomerGroup(int customerGroupId)
        {
            if (customerGroupId <= 0) return;
            using (var context = new MonkeyWarrantyEntities())
            {
                var customerGroup = context.CustomerGroups.First(g => g.Id == customerGroupId);

                context.DeleteObject(customerGroup);

                context.SaveChanges();
            }
        }

        public int GetMaxId()
        {
            var maxId = 0;

            using (var context = new MonkeyWarrantyEntities())
            {
                var customerGroup = context.CustomerGroups.OrderByDescending(x => x.Id).FirstOrDefault();
                if (customerGroup != null) maxId = customerGroup.Id;
            }

            return maxId;
        }

        public int GetCurrentIdentity()
        {
            long? identity;
            using (var context = new MonkeyWarrantyEntities())
            {
                identity = context.GetIdentity("CustomerGroups").SingleOrDefault();
            }

            return identity.HasValue ? (int)identity.Value : 0;
        }

        public CustomerGroup GetById(int id)
        {
            using (var context = new MonkeyWarrantyEntities())
            {
                return context.CustomerGroups.FirstOrDefault(x => x.Id == id);
            }
        }
    }
}
